<?php
class InstallService
{
	private $adminDao;
	
	public function __construct(){
		$this->adminDao			= new AdminDao();
	}
	
	public function runSql($prefix,$sql) {
		$sql 		= str_replace("\r", "\n", str_replace(' pisces_', ' '.$prefix, $sql));
		$ret 		= array();
		$num 		= 0;
		foreach(explode(";\n", trim($sql)) as $query)
		{
			$queries 	= preg_split("/\n+/", trim($query));
			$ret[$num]	= '';
			foreach($queries as $query)
			{
				$tmp		= trim($query);
				$ret[$num] 	.= $tmp[0] == '#' || $tmp[0].$tmp[1] == '--' ? '' : $query;
			}
			$num++;
		}
		
		foreach($ret as $query)
		{
			$query 	= trim($query);
			
			if($query)
			{
				if(substr($query, 0, 12) == 'CREATE TABLE')
				{
					$name 	= preg_replace("/CREATE TABLE\s+([a-z0-9_]+) .*/is", "\\1", $query);
					
					$this->adminDao->getDbh()->query($this->createTable($query));
					
					if(mysql_errno())
					{
						$this->showJsMessage('创建表 '.$name.' 出错:'.mysql_error());
					}
					else
					{
						$this->showJsMessage('创建表 '.$name.' 成功');
					}
				}
				else
				{
					$this->adminDao->getDbh()->query($query);
				}
			}
		}
	}
	
	private function showJsMessage($message)
	{
		echo '<script type="text/javascript">showMessage(\''.addslashes($message).' \');</script>'."\r\n";
		flush();
		ob_flush();
	}
	
	private function createTable($sql, $dbCharset='UTF8')
	{
		$type 		= strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $sql));
		$type 		= in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM';
		return 		preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql).(mysql_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=$dbCharset" : " TYPE=$type");
	}
}
?>